﻿#include "salesman.h"

#include "../../include/iframework.h"
#include "../../include/icommon.h"
#include "../../include/ilogger.h"
#include "../../include/inetcomm.h"
#include "../../include/iconfig.h"

CSalesman::CSalesman()
{
    m_timer001 = NULL;
    m_pSaleswoman = NULL;
}

CSalesman::~CSalesman()
{

}

int CSalesman::Init()
{
    m_pLogger->WriteLog("CSaleman::Init()");
    m_pFramework->GetConfig(&m_pConfig);
    m_pFramework->GetNetComm(&m_pNetComm);
    m_pFramework->GetCommon(&m_pCommon);
    connect(this,&CSalesman::sigPostTrdMsg,this,&CSalesman::slotGetTrdMsg);
    this->moveToThread(&m_thread);
    m_thread.start();
    return 1;
}

int CSalesman::UnInit()
{
    m_pLogger->WriteLog("CSalesman::UnInit()");
    m_thread.quit();
    if(m_thread.wait())
    {
        m_thread.terminate();
        m_thread.wait(3000);
    }
    return 1;
}

int CSalesman::SetFramework(IFramework *pFrm)
{
    m_pFramework = pFrm;
    m_pFramework->GetLogger(&m_pLogger);
    return 1;
}

int CSalesman::PostThreadMsg(int nType, QString data)
{
    emit sigPostTrdMsg(nType, data);
    return 1;
}

void CSalesman::slotGetTrdMsg(int nType, QString msg)
{
    qDebug() << "CSalesman::slotGetTrdMsg thread id=" << QThread::currentThreadId();
    switch(nType)
    {
    case trd_salesman_test:
    {
        if(NULL == m_timer001){
            m_timer001 = new QTimer;
            connect(m_timer001,&QTimer::timeout, this, &CSalesman::slotTimer001, Qt::QueuedConnection);
        }
        if(!m_timer001->isActive())
            m_timer001->start(200);
    }
        break;
    case message_circle_salesman_test:
    {
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(msg.toUtf8(),&error);
        if(error.error == QJsonParseError::NoError)
        {
            QJsonObject obj = doc.object();
            QString cmd = obj.take("cmd").toString();
            QString tts = obj.take("tts").toString();
            QString szLog = QString("cmd = %1, tts=%2").arg(cmd).arg(tts);
            qDebug() << szLog.toUtf8().data();
            //ui-cb
            pfnUICommBridge pfn = NULL; void *userdata = NULL;
            m_pFramework->GetCBUICommBridge(&pfn, (void**)&userdata);
            UI_Comm_Bridge rst;
            rst.msgtype = message_circle_salesman_test;
            rst.data = u8"我收到了" + szLog;
            pfn(&rst, userdata);
        }
    }
        break;
    default:break;
    }
}

void CSalesman::slotTimer001()
{
    qDebug() << "CSalesman::slotTimer001() thread id=" << QThread::currentThreadId();
    static int testCount = 0;
    testCount++;
    QString szLog = QString("salesman test msg timer count=%1").arg(testCount);
    m_pLogger->WriteLog(szLog);
    if(NULL == m_pSaleswoman)
        m_pFramework->GetSaleswoman(&m_pSaleswoman);
    m_pSaleswoman->PostThreadMsg(trd_saleswoman_test, "");
}
